package com.kim.consumers.rabbitmq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

/**
 * @author KimWu
 * @date 2020/6/18 16:49
 * @Description ：
 */
@Slf4j
@Component
@RabbitListener(
        //绑定队列
        bindings = @QueueBinding(
                //需要指定queue的名字
                value = @Queue(
                        //配置队列名称
                        value = "${rabbitmq.dlx.name}",
                        //是否是一个可删除的临时队列 --> 消息持久化
                        autoDelete = "false"
                ),
                //配置交换器
                exchange = @Exchange(
                        //指定交换器名称
                        value = "${rabbitmq.dlx.exchange}",
                        //指定具体的交换器类型,有常量类指定
                        type = ExchangeTypes.DIRECT
                ),
                //路由键
                key = "${rabbitmq.dlx.routingkey}"
        )
)
public class DriverListen {


    /**
     * 接受消息的方法，采用消息队列监听机制
     */
    @RabbitHandler
    public void pay(String msg, Message message, Channel channel) throws Exception {
        log.info("consumers 接受到了 rabbitmq 消息 {}", msg);
        //消费者手动ack机制
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        /**
         * 下面代码测试异常重试机制
         */
//        try {
//            int i = 1 / 0;
//        } catch (Exception e) {
//            //如果不抛出异常，catch之后无法重试
//            throw new RuntimeException("我异常了");
//        }
    }
}
